package main.Communication;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import main.Communication.Interface.ServerInterface;

/**
 * 服务器类 
 * 建立服务器，为其他主机提供服务
 * @author svitter
 *
 */
public class Server implements ServerInterface{
	private int PORT = 8888;
	private boolean started = false;
	private int uid = 0;

	ServerSocket ss = null;
	List<chatClient> clients = new ArrayList<chatClient>(); // 保存客户端线程类

	public Server() {
		System.out.println("[Server]: Start server ...");
		start();
	}

	public Server(int PORT) {
		this.PORT = PORT;
	}

	/**
	 * 准备，用于等待用户加入
	 */
	public void start() {
		try {
			ss = new ServerSocket(PORT); // 建立服务端对象
			started = true;

			// 监视端口
			System.out
					.println("[Server]: Server is running @localhost:" + PORT);
			waiting();
		} catch (BindException e) {
			System.out.println("端口使用中...");
		} catch (IOException e) {
			e.printStackTrace();
		}
		waiting();
	}

	/**
	 * 等待客户端键入
	 */
	public void waiting() {
		try {
			/** someone add */
			while (started) { 
				// 接收客户端
				Socket socket = ss.accept();

				// 申请一个位置
				chatClient c = new chatClient(socket, allocateID());
				new Thread(c).start();
				clients.add(c);

				System.out.println("[Server]: No. " + c.getUID() + " added");
				System.out.println("[Server]: " + c.getUID() + " people added.");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ss.close();
			} catch (IOException e) {
				System.out.println("[Server]: 等待错误");
				e.printStackTrace();
			}
		}

	}
	
	

	/**
	 * 分配用户id
	 * @return
	 */
	private int allocateID() {
		return ++uid;
	}
	
	
	/** 
	 * 所有用户均能接受到的信息
	 */
	public void boardCast(Object mes) {
		for (int i = 0; i < clients.size(); i++) {
			chatClient c = clients.get(i);
			c.send(mes);
		} 
	}
	
	

	/**
	 * 服务器退出，结束游戏
	 * @throws IOException
	 */
	public void stop() throws IOException {
		for (int i = 0; i < clients.size(); i++) {
			chatClient c = clients.get(i);
			exitClient(c);
		}
	}

	private void exitClient(chatClient c) throws IOException {
		c.getDis().close();
		c.getSocket().close();
		c.getDos().close();
	}

	/**
	 * 踢出用户
	 * @param c
	 * @throws IOException
	 */

	public void kickoff(int uid) {
		// TODO Auto-generated method stub
		
	}
}
